package com.atguigu.tingshu.user.strategy.cilent;

import com.atguigu.tingshu.user.strategy.domain.CommonLoginParam;
import com.atguigu.tingshu.user.strategy.service.Login;
import com.atguigu.tingshu.user.strategy.anno.LoginStrategy;
import com.atguigu.tingshu.user.strategy.enums.LoginType;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class LoginClient implements ApplicationContextAware {

    private final Map<LoginType, Login> MAP = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beansMap = applicationContext.getBeansWithAnnotation(LoginStrategy.class);
        if (!CollectionUtils.isEmpty(beansMap)) {
            beansMap.values().forEach(bean -> {
                LoginStrategy anno = bean.getClass().getAnnotation(LoginStrategy.class);
                LoginType loginType = anno.type();
                MAP.put(loginType, (Login) bean);
            });
        }
    }

    public Map<String, String> login(LoginType type, CommonLoginParam loginParam) {
        return MAP.get(type).login(loginParam);
    }
}
